/*
 * ServiceSearcherAgent.java
 *
 * Created on 7 novembre 2007, 16.21
 *
 * @version 1.1
 * @author Federico Paparoni
 *
 */

package com.javastaff.btfree;

import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class ServiceSearcherAgent implements DiscoveryListener{

    private DiscoveryAgent agent;

    private ServiceSearcher serviceSearcher;

    private Vector devicesFound;

    private LocalDevice localDevice;
    
    private int[] attrSet = {0x0100};
    private UUID[] uuidSet = new UUID[1];
    
    private String SERVICE_NAME="";
    
    private ServiceRecord service;
    
    public ServiceSearcherAgent(ServiceSearcher serviceSearcher, String uuid, RemoteDevice device, String name) {
        try {
            this.serviceSearcher=serviceSearcher;
            this.devicesFound=new Vector();
            this.SERVICE_NAME=name;
            localDevice = LocalDevice.getLocalDevice();
            agent = localDevice.getDiscoveryAgent();
            uuidSet[0] = new UUID(uuid,false);
            agent.searchServices(attrSet, uuidSet, device, this);
        } catch (BluetoothStateException ex) {
            serviceSearcher.signalError(ex.toString());
        }
    }

    public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
    }

    public void servicesDiscovered(int i, ServiceRecord[] serviceRecord) {
        for(int j = 0; j < serviceRecord.length; j++) {
            DataElement serviceNameElement = serviceRecord[j].getAttributeValue(0x0100);
            String serviceName = (String)serviceNameElement.getValue();
            if ((serviceName!=null)&&(serviceName.equals(SERVICE_NAME))){
                service = serviceRecord[j];
                break;
            }
        }
    }

    public void serviceSearchCompleted(int i, int i0) {
        serviceSearcher.serviceFound(service);
    }

    public void inquiryCompleted(int i) {
    }
    
}
